package com.howie.parnote.interceptor;

import com.howie.parnote.util.security.CSRFTokenManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>Title: parnote</p>
 * <p>
 * Description: parnote
 * </p>
 *
 * @author huangyan
 *         Created by HY on 2015/1/17 0017.
 * @version v1.0.0
 */
public class CSRFTokenInterceptor extends HandlerInterceptorAdapter {

	/*@Value("${ignore_urls}")
	private String ignoreUrl;
	@Value("${parnote_home_url}")
	private String homeUrl;*/

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		String requestUrl = request.getRequestURI();

		//获取ip地址
//		System.out.println(getRemortIP(request));
//		String[] urls = ignoreUrl.split(",");

//		boolean beFilter = true;
		/*boolean beFilter = false;
		for (String url : urls) {
			if (ignoreable(requestUrl, url)) {
				beFilter = false;
				break;
			}
		}*/

		/*if (beFilter) {
			HttpSession session = request.getSession();
			SharerModule sharer = SharerUtil.getSharer(session);
			if (sharer == null) {
				// 判断是否为ajax请求,是的话则不为空
				String requestType = request.getHeader("X-Requested-With");
				if (StringUtil.isEmpty(requestType)) {
					response.sendRedirect("login");
				} else {
					response.setContentType("html");
					PrintWriter writer = response.getWriter();
					writer.println("<script type=\"text/javascript\" >");
					writer.println("window.location.href='/parnote/login';");
					writer.println("</script>");
				}
				return false;
			}
		}*/


		if (request.getMethod().equalsIgnoreCase("POST")) {
			String sessionToken = CSRFTokenManager.getTokenFromSession(request.getSession());
			String requestToken = CSRFTokenManager.getTokenFromRequest(request);
			if (sessionToken.equals(requestToken)) {
				return true;
			} else {
				response.sendError(HttpServletResponse.SC_FORBIDDEN, "Bad or missing CSRF value");
				return false;
			}
		}

		return super.preHandle(request, response, handler);
	}

	private String getRemortIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}

//	private boolean ignoreable(String requestUrl, String url) {
//		return requestUrl.equals(homeUrl) || requestUrl.endsWith(url);
//	}
}
